package com.nyf.web;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.nyf.dao.DocumentDao;
import com.nyf.entity.Document;

public class FolderServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method=request.getParameter("m");
		if(method==null||"".equals(method)){
			folder(request,response);
			
		}else if("upload".equals(method)){
			upload(request,response);
			
		}else if("list".equals(method)){
			list(request,response);
		}else if("add".equals(method)){
			add(request,response);
		}else if("add2".equals(method)){
			add2(request,response);
		}else{
			response.sendError(404);
		}
		
	}


	private void add2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		String name=request.getParameter("name");
		String id=request.getParameter("n");
		String kind="folder";
		DocumentDao dao=new DocumentDao();
		Document doc=new Document();
		doc.setName(name);
		doc.setFilename(id);
		doc.setFileid(UUID.randomUUID().toString());
		doc.setKind(kind);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=sdf.format(date);
		
		doc.setTime(time);
		dao.save(doc);
		HttpSession session=request.getSession();
		session.setAttribute("doc", doc);
		DocumentDao dao2=new DocumentDao();
		List<Document> list=dao2.findAll();
		request.setAttribute("list", list);
		response.sendRedirect("folder.jspx?m=list");
	}


	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		request.getRequestDispatcher("/WEB-INF/views/folder.jsp").forward(request, response);
		
	}


	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		DocumentDao dao=new DocumentDao();
		String id=request.getParameter("id");
		
		List<Document> list=dao.findByfileId(id);
		
		request.setAttribute("list", list);
		request.getRequestDispatcher("/WEB-INF/views/list.jsp").forward(request, response);
	}


	private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		File uploadfile=new File("e:/upload");
		File tempfile=new File("e:/uploadtemp");
		String id=request.getParameter("h");
		
		if(!uploadfile.exists()) {
			uploadfile.mkdir();
		}
		
		if(!tempfile.exists()) {
			tempfile.mkdir();
		}
		
		Document doc=new Document();
		
		if(ServletFileUpload.isMultipartContent(request)){
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			factory.setSizeThreshold(1024*10);
			
			factory.setRepository(tempfile);
			
			ServletFileUpload uploader = new ServletFileUpload(factory);
			
			uploader.setFileSizeMax(1024*1024*10);
			
			try {
				List<FileItem> list = uploader.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){
						if("desc".equals(item.getFieldName())) {
							doc.setName(item.getString());
						}
						
					}else{
						
						String name=item.getName();
						String extendName=name.substring(name.lastIndexOf("."));
						
						String newName = UUID.randomUUID().toString() + extendName;
						Date date = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time=sdf.format(date);
						InputStream stream = item.getInputStream();
						
						FileOutputStream outputStream = new FileOutputStream(new File(uploadfile,newName));
						
						byte[] buffer = new byte[1024];
						
						int len = -1;
						
						while((len = stream.read(buffer)) != -1) {
							outputStream.write(buffer, 0, len);
						}
						outputStream.flush();
						outputStream.close();
						doc.setTime(time);
						doc.setName(extendName);
						doc.setFilename(newName);
						doc.setFileid(id);
					}
					
				}
				DocumentDao dao = new DocumentDao();
				dao.save(doc);
				
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			response.sendError(404);
			
		}
		response.sendRedirect("floder.jspx?m=list");
	}


	private void folder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		
		String name=request.getParameter("name");
		String kind="folder";
		DocumentDao dao=new DocumentDao();
		Document doc=new Document();
		doc.setName(name);
		doc.setFilename("folder");
		doc.setFileid(UUID.randomUUID().toString());
		doc.setKind(kind);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=sdf.format(date);
		doc.setTime(time);
		dao.save(doc);
		HttpSession session=request.getSession();
		session.setAttribute("doc", doc);
		response.sendRedirect("main.jspx");
		
	}
}
